package com.bwie.orders.sync;

import com.bwie.common.redis.service.RedisService;

import com.bwie.orders.mapper.OrderMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.Collection;

@Component
public class RedisInventorySync {
    /**
     * 引入
     */
    @Autowired
    private RedisService redisService;
    @Autowired
    private OrderMapper mapper;

    /**
     * 定时器同步redis到数据库
     */
    @Scheduled(cron = "0 0 0 * * ?")
    public void redisInventorySync(){
        //获取所有的key
        Collection<String> keys = redisService.keys("ProductInventoryLhc:*");
        //非空判断
        if (keys!=null){
            //循环
            keys.forEach(key ->{
                //切割
                String[] split = key.split(":");
                //根据skuId获得商品数量
                Integer num = (Integer) redisService.redisTemplate.opsForValue().get("ProductInventoryLhc:" + split[1]);
                //修改数据库商品数量
                mapper.updInventory(Integer.valueOf(split[1]),num);
            });
        }
    }
}
